import React, { Component } from 'react';
import DateUtil from '../../util/DateUtil';
import { fetchReaderReserve, cleanReserve, readerAttend } from '../../api/index';

import { setImage } from '../../util/imageUtil';
import { Toast, Modal, Card, Flex, Button, Checkbox, ListView } from 'antd-mobile';
const alert = Modal.alert;

interface Props {
  offset: number;
  limit: number;
  query: string;
  maxSize: number;
  coatBody?: React.ReactElement<any>;
  undershirtBody?: React.ReactElement<any>;
  history?: any;
}
interface State {
  dataSource?: any;
  isLoading?: boolean;
  height?: number;
  hasMore?: boolean;
  dataArray: any[];
  limit: number;
  refreshing: boolean;
  offset: number;
  totalSize: number;
  query: string;
  actionInfo: boolean;
  message: string
  modal1: boolean
}
function MyBody(props: any) {
  return <div className="myp-drop">{props.children}</div>;
}
function SmallBody(props: any) {
  return <div style={{ marginTop: '60px' }}>{props.children}</div>;
}
class index extends Component<Props, State> {
  constructor(props: Props) {
    super(props);

    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1: any, row2: any) => row1 !== row2,
    });

    this.state = {
      offset: this.props.offset,
      refreshing: true,
      query: this.props.query || 'isDel = 0 and approval = 1',
      limit: this.props.limit,
      totalSize: 0,
      dataSource,
      isLoading: true,
      hasMore: true,
      dataArray: [],
      actionInfo: false,
      message: '',
      modal1: false
    };
  }


  loadData = () => {
    let then = this;
    const params = {
      offset: this.state.offset * this.state.limit,
      limit: this.state.limit,
      query: this.props.query || this.state.query,
    };

    fetchReaderReserve(params).then((response: any) => {
      const list = response.data.webReserveGroup;
      if (!!list) {
        const dataArr = this.state.dataArray.concat(list);
        let hasMore = true;
        if (dataArr.length >= response.data.totalRecords) {
          hasMore = false;
        }
        this.setState(
          {
            dataArray: dataArr,
            totalSize: response.data.totalRecords,
            dataSource: this.state.dataSource.cloneWithRows(dataArr),
            isLoading: false,
            hasMore, // 下拉刷新后，重新允许开下拉加载
            refreshing: false, // 是否在刷新数据
          },
          () => {
            this.state.dataArray.map((a: any, index: number) => {
              if (!a['image']) {

                setImage(a, index).then((value: any) => {
                  let dom = document.getElementById(a.partyId);
                  if (dom) {
                    dom.setAttribute('src', value);
                  }
                });
              }
            });

            let dataSource = then.state.dataSource.cloneWithRows(this.state.dataArray);
            then.setState({
              dataSource,
            });
          }
        );
      } else {
        this.setState({
          refreshing: false,
          isLoading: false,
          hasMore: false,
        });
        return false;
      }
    });
  };
  imageLoad = (image: any, index: number) => {
    this.setState((preState) => {
      const dataArray = preState.dataArray;
      const dataSource = preState.dataSource;
      dataArray[index].image = image;

      dataSource.cloneWithRows(dataArray);
      return {
        dataArray,
        dataSource,
      };
    });
  };
  cleanList = (value: any) => {
    this.setState({
      dataArray: value,
    });
  };
  // 滑动到底部时加载更多
  onEndReached = (event: any) => {
    // 加载中或没有数据了都不再加载

    const offset = this.state.offset + 1;

    if (this.state.isLoading || !this.state.hasMore) {
      return;
    }

    this.setState(
      {
        isLoading: true,
        offset,
      },
      () => {
        this.loadData();
      }
    );
  };
  render() {

    const { history } = this.props;

    const separator = (sectionID: any, rowID: any) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    const row = (item: any, sectionID: any, rowID: string | number | undefined) => {
      return (
        <Card key={rowID}>
          <Card.Header
            title={
              <div
                style={{
                  width: '150px',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  fontSize: '14px',
                  fontWeight: 500,
                }}>
                {item.partyName}
              </div>
            }
            extra={
              <span style={{ fontSize: '14px' }}>{item.reserveStatus == 0 ? '未审核' : '已审核'}</span>
            }
          />
          <Card.Body>
            <Flex>
              <Flex.Item style={{ width: '2.2rem', height: '1.36rem', minWidth: '100px', flex: 'none' }}>
                <img alt="图片加载中..." src={item.image} id={item.partyId} />
              </Flex.Item>
              <Flex.Item style={{ height: '1.36rem' }}>
                <ul>
                  <li style={{ fontWeight: 500, fontSize: '12px' }}>
                    报名时间：{DateUtil.baseFormat(item.reserveDate)}
                  </li>
                  <li style={{ fontWeight: 500, fontSize: '12px' }}>
                    活动时间：{DateUtil.baseFormat(item.partyStartDate)}
                  </li>
                  <li style={{ fontWeight: 500, fontSize: '12px' }}>活动地点：{item.partyVenue}</li>
                </ul>
              </Flex.Item>
            </Flex>
          </Card.Body>
          <Card.Footer
            extra={
              <div style={{ height: '50px', paddingTop: '12px' }}>
                {/* <Button type="primary" inline size="small" onClick={() => {
                        history.push('/appraisal_form/' + item.partyId + '/' + item.reserveId)
                      }}  >
                        评价
                     </Button> */}
                {item.attendState === 5 ? (
                  <Button
                    type="primary"
                    inline
                    size="small"
                    style={{ marginRight: '4px' }}
                    onClick={(e) => this.cancelSignConfirm(item.reserveId)}>
                    {' '}
                    取消参加
                  </Button>
                ) : (
                    ''
                  )}
                {item.reserveStatus === 1 && item.attendState === 5 ? (
                  <Button
                    type="primary"
                    inline
                    size="small"
                    onClick={(e) => this.setReaderHoliday(item.reserveId)}
                    style={{ marginRight: '4px' }}>
                    {' '}
                    请假
                  </Button>
                ) : (
                    ''
                  )}
                {item.attendState === 1 ? (
                  <Flex>
                    <Flex.Item><Button type="warning"  inline size="small" className="am-button-borderfix" disabled>
                      已签到{' '}
                    </Button></Flex.Item>
                    {
                      item.score === '0' ? <Flex.Item> <Button type="primary" inline size="small" onClick={() => {
                        history.push('/appraisal_form/' + item.partyId + '/' + item.reserveId)
                      }}  >
                        评价
                     </Button></Flex.Item> : <Flex.Item> <Button type="warning" inline size="small" disabled
                        >
                          已评价
                     </Button></Flex.Item>
                    }
                  </Flex>
                ) : (
                    ''
                  )}
                {item.attendState === 0 ? (
                  <Button type="warning" inline size="small" className="am-button-borderfix" disabled>
                    缺席
                  </Button>
                ) : (
                    ''
                  )}
                {item.attendState === 2 ? (
                  <Button type="warning" inline size="small" className="am-button-borderfix" disabled>
                    迟到
                  </Button>
                ) : (
                    ''
                  )}
                {item.attendState === 3 ? (
                  <Button type="warning" inline size="small" className="am-button-borderfix" disabled>
                    请假
                  </Button>
                ) : (
                    ''
                  )}
                {item.attendState === 4 ? (
                  <Button type="warning" inline size="small" className="am-button-borderfix" disabled>
                    早退
                  </Button>
                ) : (
                    ''
                  )}
              </div>
            }
          />
        </Card>
      );
    };
    return (
      <ListView
        style={{ height: window.innerHeight }}
        dataSource={this.state.dataSource}
        className="am-list sticky-list"
        renderFooter={() => (
          <div style={{ padding: 30, textAlign: 'center', marginTop: 40 }}>
            {this.state.isLoading ? '加载中...' : '加载完毕'}
          </div>
        )}
        renderRow={(r, s, h) => row(r, s, h)}
        initialListSize={10}
        pageSize={10}
        onEndReachedThreshold={50}
        renderSeparator={separator}
        renderBodyComponent={() => this.props.coatBody || <MyBody />}
        renderSectionBodyWrapper={() => this.props.undershirtBody || <SmallBody />}
        onEndReached={this.onEndReached}
      />



    );
  }
  setReaderHoliday(arg0: string): void {
    let then = this;
    alert('请假', '确认请假???', [
      { text: '取消', onPress: () => console.log('cancel') },
      {
        text: '确认',
        onPress: () => {
          then.attend(arg0,true)
        },
      },
    ]);
  }
  attend = (id: string, flag: boolean) => {
    let then = this;
    let action = 2;
    let title = '签到';
    if (flag) {
      action = 1;
      title = '请假';
    }
    let barcode = sessionStorage.getItem('barcode');
    const params = {
      barcode: barcode,
      partyId: id,
      action,
    };

    readerAttend(params)
      .then((response: any) => {
        try {
          if (response['errors']) {
            let error = response.errors[0];
            console.log(error);
            let msg = !!error.message ? error.message : '该活动暂时无法签到, 请稍后再试! ';
            then.resultInfo(title + '失败！', false);
            return false;
          } else {
            let data = response.data;
            if (!data.state) {
              then.resultInfo(title + '失败！', false);
              return;
            }
            then.resultInfo(title + '成功！', true);
          }
        } catch (e) {
          then.resultInfo(title + '失败！', false);
        }
      })
      .catch((e) => {
        then.resultInfo(e, false);
      });
  };
  cancelSignConfirm(arg0: string): void {
    let then = this;
    alert('取消参加', '确认取消参加???', [
      { text: '取消', onPress: () => console.log('cancel') },
      {
        text: '确认',
        onPress: () => {
          let requestData = {
            reserveId: arg0,
          };

          cleanReserve(requestData)
            .then((response: any) => {
              if (response['errors']) {
                try {
                  let error = response.errors[0];
                  console.log(error);
                  let msg = !!error.message
                    ? error.message
                    : '该活动暂时无法取消报名参与, 请稍后再试! ';
                  then.resultInfo('取消失败！', false);
                  return false;
                } catch (e) {
                  then.props.history.go(0);
                }
              } else {
                then.resultInfo('取消成功！', true);
              }
            })
            .catch((e) => {
              console.log(e);
              then.resultInfo('取消失败！', false);
            });
        },
      },
    ]);
  }
  resultInfo = (message: any, flag: boolean) => {
    let then = this;
    if (flag) {
      Toast.success(message);
      const query = sessionStorage.getItem('query');

      this.setState(
        {
          dataArray: [],
          query: query || '',
        },
        () => {
          then.loadData();
        }
      );
    } else {
      Toast.fail(message);
      const query = sessionStorage.getItem('query');
      this.setState(
        {
          dataArray: [],
          query: query || '',
        },
        () => {
          then.loadData();
        }
      );
    }
  };
}

export default index;
